package com.lkd.handler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.ConsulConfig;
import com.lkd.config.TopicConfig;
import com.lkd.contract.VendoutResultContract;
import com.lkd.emq.Topic;
import com.lkd.entity.ChannelEntity;
import com.lkd.entity.VendoutRunningEntity;
import com.lkd.exception.LogicException;
import com.lkd.service.ChannelService;
import com.lkd.service.VendoutRunningService;
import com.lkd.utils.DistributedLock;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-12-21 10:51
 */
@Component
@Topic(TopicConfig.VMS_RESULT_TOPIC)
@Slf4j
public class VendOutResultHandler implements MsgHandler {

    @Autowired
    private VendoutRunningService vendoutRunningService;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private ConsulConfig consulConfig;
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public void process(String jsonMsg) throws IOException {

        //1.接收消息，判断消息参数
        VendoutResultContract result = JsonUtil.getByJson(jsonMsg, VendoutResultContract.class);
        if(result == null || result.getVendoutData() == null ||
                StringUtils.isEmpty(result.getVendoutData().getOrderNo())
                || StringUtils.isEmpty(result.getInnerCode())
                || StringUtils.isEmpty(result.getVendoutData().getChannelCode())
        ){
            return;
        }

        //进入下单流程，加锁
        DistributedLock distributedLock =
                new DistributedLock(consulConfig.getConsulRegisterHost(), consulConfig.getConsulRegisterPort());
        //创建锁对象
        String lockName = "lock-" + result.getInnerCode();
        //获取sessionId
        String sessionId = (String) redisTemplate.opsForValue().get(VMSystem.VM_LOCK_KEY_PREF + lockName);
        //解锁
        distributedLock.releaseLock(sessionId);

        //2.判断是否成功
        if(result.isSuccess()){
            //成功，修改流水状态
            vendoutRunningService.update(Wrappers.<VendoutRunningEntity>lambdaUpdate()
                    .eq(VendoutRunningEntity::getOrderNo,result.getVendoutData().getOrderNo())
                    .set(VendoutRunningEntity::getStatus,true)
            );
        }else{
            //失败，回滚库存
            channelService.update(Wrappers.<ChannelEntity>lambdaUpdate()
                    .setSql("current_capacity = current_capacity + 1")
                    .eq(ChannelEntity::getInnerCode,result.getInnerCode())
                    .eq(ChannelEntity::getChannelCode,result.getVendoutData().getChannelCode())
            );
        }

    }
}
